﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.Script.Serialization;

namespace DVK.SP2007
{
    /// <summary>
    /// Gets the user information from "User Information List" based on userId.
    /// This works with WSS 3.0.
    /// </summary>
    public class WssUserInfoManager : IUserInfoManager<int>
    {
        SPList _userInfoList;
        IMapping _mapping;

        /// <summary>
        /// Initializes a new instance of the <see cref="WssUserInfoManager"/> class.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="userinfoListUrl">The userinfo list url.</param>
        /// <param name="mapping">The mapping.</param>
        public WssUserInfoManager(SPWeb web, string userinfoListUrl, IMapping mapping)
        {
            _userInfoList = web.GetList(userinfoListUrl);
            _mapping = mapping;
        }

        #region IUserInfoManager Members

        /// <summary>
        /// Gets the user info from WSS user information list.
        /// Uses the mapping info in configuration to get PersonMetadata.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        public PersonMetadata GetUserInfo(int userId)
        {
            //gets user info
            SPListItem userInfo = _userInfoList.GetItemById(userId);

            //Create JSON string for metadata to deserialize it
            StringBuilder metadataJSON = new StringBuilder(100);

            metadataJSON.Append("{");
            foreach (var item in _mapping.GetMapping())
            {
                //item.Key is PersonMetadata Property name
                //item.Value is Sharepoint 2007 metadata field name
                if (!_userInfoList.Fields.ContainsField(item.Value))
                    continue;

                string metadata = userInfo[item.Value] as string;
                metadataJSON.AppendFormat(
                    "\"{0}\":\"{1}\",", 
                    item.Key, //PersonMetadata Property name
                    string.IsNullOrEmpty(metadata) ? string.Empty : metadata); //metadata value
            }
            if (metadataJSON[metadataJSON.Length-1] == ',')
                metadataJSON.Remove(metadataJSON.Length-1,1); //Remove last ",", it not needed. Remove is fast.
            metadataJSON.Append("}");

            PersonMetadata personMetadata = 
                new JavaScriptSerializer().Deserialize<PersonMetadata>(metadataJSON.ToString());

            return personMetadata;
        }

        #endregion
    }
}
